package org.larkdoc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.larkdoc.constant.ViewConts;
import org.larkdoc.model.bo.ProjectBO;
import org.larkdoc.model.entity.ProjectInfo;
import org.larkdoc.model.entity.ProjectRelGroup;
import org.larkdoc.model.entity.ProjectRelUser;
import org.larkdoc.model.entity.UserInfo;
import org.larkdoc.model.vo.PageVO;
import org.larkdoc.model.vo.ProjectVO;
import org.larkdoc.model.vo.RespBaseVO;
import org.larkdoc.model.vo.UserVO;
import org.larkdoc.service.ProjectRelUserService;
import org.larkdoc.service.ProjectService;
import org.larkdoc.service.UserService;
import org.larkdoc.util.AuthUtil;
import org.larkdoc.util.DozerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;

/**
 * 项目管理控制类
 * 
 * @author  zhangpeijun[zhangpeijun1024@qq.com]
 * @version  [v1.0.1, 2017年10月17日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@RestController
@RequestMapping("/project")
public class ProjectController {
    
    private final static Logger log = LoggerFactory.getLogger(ProjectController.class);
    
    @Autowired
    ProjectService              projectService;
    
    @Autowired
    UserService                 userService;
    
    @Autowired
    ProjectRelUserService       projectRelUserService;
    
    @RequestMapping("/create")
    @ResponseBody
    public RespBaseVO create(ProjectVO projectVO) {
        RespBaseVO respVo = new RespBaseVO();
        ProjectBO bo = projectVO2BO(projectVO);
        bo.setCreator(AuthUtil.getAccount());
        if (projectService.insertSelective(bo) != 1) {
            respVo.setRetCode(ViewConts.Code.FAILURE);
            respVo.setRetMsg(ViewConts.Msg.FAILURE);
        } else {
            // 返回数据给调用者
            respVo.setRetVal(bo.getId());
        }
        return respVo;
    }
    
    @RequestMapping("/delete/{id}")
    public RespBaseVO delete(@PathVariable int id) {
        RespBaseVO respVo = new RespBaseVO(ViewConts.Code.FAILURE, ViewConts.Msg.FAILURE, null);
        if (id > 0) {
            ProjectInfo project = projectService.selectByPrimaryKey(id);
            if (null != project && AuthUtil.getAccount().equals(project.getCreator())) {
                if (projectService.deleteByPrimaryKey(id) == 1) {
                    respVo.setRetCode(ViewConts.Code.SUCCESS);
                    respVo.setRetMsg(ViewConts.Msg.SUCCESS);
                }
            }
        }
        return respVo;
    }
    
    @RequestMapping("/delete/batch")
    public RespBaseVO deleteBatch(@RequestParam("ids[]") int[] ids) {
        // jquey传递数组到后台，需要用“ids[]”获取
        RespBaseVO respVo = new RespBaseVO(ViewConts.Code.FAILURE, ViewConts.Msg.FAILURE, null);
        if (null != ids && ids.length > 0) {
            int result = projectService.deleteByIdsAndAccount(ids, AuthUtil.getAccount());
            if (result > 0) {
                respVo.setRetCode(ViewConts.Code.SUCCESS);
                respVo.setRetMsg(ViewConts.Msg.SUCCESS);
                respVo.setRetVal("成功删除：" + result + " 条数据。");
            }
        } else {
            respVo.setRetVal("请求删除数据为空。");
        }
        return respVo;
    }
    
    @RequestMapping("/get/{id}")
    public RespBaseVO getById(@PathVariable int id) {
        RespBaseVO respVo = new RespBaseVO();
        if (id > 0) {
            ProjectInfo proInfo = projectService.selectByPrimaryKey(id);
            boolean queryFlag = false;
            if (null != proInfo) {
                if (AuthUtil.getAccount().equals(proInfo.getCreator())) {
                    queryFlag = true;
                } else {
                    UserInfo user = userService.getByAccount(AuthUtil.getAccount());
                    if (projectRelUserService.checkUserBelongProject(proInfo.getId(), user.getId())) {
                        queryFlag = true;
                    }
                }
                if (queryFlag) {
                    ProjectVO vo = DozerUtil.conversion(proInfo, ProjectVO.class);
                    vo.setUsers(userInfo2VO(userService.queryByProjectId(proInfo.getId())));
                    respVo.setRetVal(vo);
                    // TODO 可考虑补充文档列表
                }
            }
        }
        return respVo;
        
    }
    
    @RequestMapping("/update")
    public RespBaseVO update(ProjectVO projectVO) {
        RespBaseVO respVo = new RespBaseVO(ViewConts.Code.FAILURE, ViewConts.Msg.FAILURE, null);
        if (null != projectVO && projectVO.getId() > 0) {
            ProjectInfo dbInfo = projectService.selectByPrimaryKey(projectVO.getId());
            String account = AuthUtil.getAccount();
            if (null != dbInfo && account.equals(dbInfo.getCreator())) {
                projectVO.setUpdateTime(new Date());
                if (projectService.updateByPrimaryKeySelective(projectVO2BO(projectVO)) == 1) {
                    respVo.setRetCode(ViewConts.Code.SUCCESS);
                    respVo.setRetMsg(ViewConts.Msg.SUCCESS);
                }
            }
        }
        return respVo;
    }
    
    @RequestMapping("/page")
    public RespBaseVO page(PageVO<ProjectVO> page) {
        log.debug("page param {}", page);
        RespBaseVO respVo = new RespBaseVO();
        ProjectVO vo = null == page.getSearch() ? page.searchMapToTargetClass(ProjectVO.class) : page.getSearch();
        vo = null == vo ? new ProjectVO() : vo;
        vo.setCreator(AuthUtil.getAccount());
        page.setSearch(vo);
        PageInfo<ProjectBO> query = projectService.page(page);
        @SuppressWarnings("unchecked")
        PageVO<ProjectVO> result = DozerUtil.conversion(query, PageVO.class);
        List<ProjectVO> proVoList = null;
        // 过滤用户信息
        if (null != query && CollectionUtils.isNotEmpty(query.getList())) {
            proVoList = new ArrayList<ProjectVO>(query.getList().size());
            ProjectVO proVo = null;
            for (ProjectBO bo : query.getList()) {
                if (null != bo) {
                    // BO转VO,其中users属性，并未从BO转成VO，需要单独进行转换操作。
                    // TODO 转换关联关系
                    proVo = DozerUtil.conversion(bo, ProjectVO.class);
                    // 过滤用户信息
                    proVo.setUsers(userInfo2VO(bo.getUsers()));
                    proVoList.add(proVo);
                }
            }
        }
        result.setList(proVoList);
        respVo.setRetVal(result);
        return respVo;
    }
    
    @RequestMapping("updateOwner")
    public RespBaseVO updateOwner(Integer projectId, Integer newOwnerId) {
        RespBaseVO respVo = new RespBaseVO(ViewConts.Code.FAILURE, ViewConts.Msg.FAILURE, null);
        UserInfo newOwner = userService.selectByPrimaryKey(newOwnerId);
        if(projectId > 0 && newOwnerId > 0 && newOwner != null ) {
            ProjectInfo dbInfo = projectService.selectByPrimaryKey(projectId);
            String account = AuthUtil.getAccount();
            if (null != dbInfo && account.equals(dbInfo.getCreator())) {
                UserInfo oldOwner = userService.getByAccount(account);
                dbInfo.setUpdateTime(new Date());
                dbInfo.setCreator(newOwner.getAccount());
                if (projectService.updateByPrimaryKeySelective(dbInfo) == 1) {
                    ProjectRelUser relUser = new ProjectRelUser();
                    // 原项目创建者增加为项目成员
                    relUser.setProjectId(dbInfo.getId());
                    relUser.setUserId(oldOwner.getId());
                    List<ProjectRelUser> projectRelUserList = new ArrayList<ProjectRelUser>(1);
                    projectRelUserList.add(relUser);
                    projectRelUserService.insertBatch(projectRelUserList);
                    log.info("Project " + dbInfo.getName() + "has been transfer from " + account + " to " + newOwner.getAccount());
                    respVo.setRetCode(ViewConts.Code.SUCCESS);
                    respVo.setRetMsg(ViewConts.Msg.SUCCESS);
                }
            } else {
                respVo.setRetMsg("没有权限");
            }
        } else {
            respVo.setRetMsg("参数错误");
        }
        return respVo;
    }
    
    private ProjectBO projectVO2BO(ProjectVO projectVO) {
        ProjectBO bo = null;
        if (null != projectVO) {
            bo = DozerUtil.conversion(projectVO, ProjectBO.class);
            bo.setUpdateTime(new Date());
            if (StringUtils.isBlank(bo.getCreator())) {
                bo.setCreator(AuthUtil.getAccount());
            }
            // 拼装项目与群组关系
            if (StringUtils.isNotBlank(projectVO.getGroupIds())) {
                String[] groupids = projectVO.getGroupIds().split(",");
                List<ProjectRelGroup> groupList = new ArrayList<ProjectRelGroup>(groupids.length);
                ProjectRelGroup relGroup = null;
                try {
                    for (String id : groupids) {
                        relGroup = new ProjectRelGroup();
                        // 新增和修改通用
                        relGroup.setProjectId(projectVO.getId());
                        relGroup.setGroupId(Integer.valueOf(id));
                        groupList.add(relGroup);
                    }
                } catch (NumberFormatException e) {
                    log.error("NumberFormatException ", e);
                    log.error("NumberFormatException ： {}", projectVO.getGroupIds());
                }
                bo.setProjectRelGroup(groupList);
            }
            // 拼装项目与用户关系。
            if (StringUtils.isNotBlank(projectVO.getUserIds())) {
                String[] userIds = projectVO.getUserIds().split(",");
                List<ProjectRelUser> userList = new ArrayList<ProjectRelUser>(userIds.length);
                ProjectRelUser relUser = null;
                try {
                    for (String id : userIds) {
                        relUser = new ProjectRelUser();
                        // 新增和修改通用
                        relUser.setProjectId(projectVO.getId());
                        relUser.setUserId(Integer.valueOf(id));
                        userList.add(relUser);
                    }
                } catch (NumberFormatException e) {
                    log.error("NumberFormatException ", e);
                    log.error("NumberFormatException ： {}", projectVO.getUserIds());
                }
                bo.setProjectRelUser(userList);
            }
        }
        return bo;
    }
    
    /**
     * info转vo，屏蔽一些用户信息
     * @param userList
     * @return [参数说明]
     * 
     * @returns List<UserVO>
     * @see [类、类#方法、类#成员]
     * @author  zhangpeijun[zhangpeijun1024@qq.com]<br/>
     *          2017年12月8日下午5:52:31
     */
    private List<UserVO> userInfo2VO(List<UserInfo> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        } else {
            List<UserVO> users = new ArrayList<UserVO>(userList.size());
            UserVO userVo = null;
            for (UserInfo user : userList) {
                if (null != user) {
                    userVo = new UserVO();
                    userVo.setAccount(user.getAccount());
                    userVo.setName(user.getName());
                    userVo.setId(user.getId());
                    users.add(userVo);
                }
            }
            return users;
        }
    }
}
